<?php

namespace App\Models\Traits;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

trait HasUserOrderFinishedCache
{
	public function finishedOrdersCacheKey(): string
	{
		return "user_{$this->id}_finished_orders";
	}

	public function addOrderToFinishedCache($cacheId)
	{
		Log::debug("Add order: {$cacheId} to finished");
		Redis::transaction(function () use ($cacheId) {
			Redis::zAdd($this->finishedOrdersCacheKey(), 1, $cacheId);
            $this->delOrderFromUnpaidCache($cacheId);
			$this->delOrderFromPendingCache($cacheId);
			$this->delOrderFromRunningCache($cacheId);
		});

		$this->delSpareFinishedRecordCache();
	}

	public function delSpareFinishedRecordCache()
	{
		$total = 30;

		$currentCount = Redis::zCard($this->finishedOrdersCacheKey());

		if ($currentCount <= $total) return;

		$spareCount = $currentCount - $total;
		$spareRecords = Redis::zRange($this->finishedOrdersCacheKey(), 0, $spareCount-1);

		foreach ($spareRecords as $cacheKey) {
			Log::debug("=== Del record: {$cacheKey}");
			$this->delMyOrderCache($cacheKey);
		}

		Redis::zRemRangeByRank($this->finishedOrdersCacheKey(), 0, $spareCount-1);
	}

	public function delRecordFromFinishedCache($cacheId)
	{
		Redis::zRem($this->finishedOrdersCacheKey(), $cacheId);
	}

	public function isRecordInFinishedCache($cacheId): bool
	{
		return Redis::zScore($this->finishedOrdersCacheKey(), $cacheId) == 1;
	}
}
